import {
	Toast
} from '@/utils/actions.js'
import store from '@/store'
import Request from '@/utils/request.js'
// 查询dom的信息
export const queryDomInfo = async (domStr, that, time = 300) => {
	that ? await that.$nextTick() : () => {};
	return new Promise((resolve, reject) => {
		let timer = setTimeout(() => {
			const query = that ? uni.createSelectorQuery().in(that) : uni.createSelectorQuery();
			const promiseArr = [];
			const allSelectArr = domStr.split(',');
			allSelectArr.forEach((item) => {
				let promiseItem = new Promise((resolve2) => {
					query.select(`${item}`).boundingClientRect(resolve2).exec();
				});
				promiseArr.push(promiseItem);
			});
			Promise.all(promiseArr).then((results) => {
				let allDomInfo = [];
				// 合并所有查询结果
				results.forEach((result) => {
					if (Array.isArray(result)) {
						// 如果是 selectAll 的结果，直接展开数组
						allDomInfo = allElementsInfo.concat(result);
					} else {
						// 如果是单个元素的结果，直接添加到数组
						allDomInfo.push(result);
					}
				});
				resolve(allDomInfo);
			});
			if (timer) {
				clearTimeout(timer);
				timer = null;
			}
		}, time);
	});
};

/**
 * 参数处理
 * @param params 参数
 */
export const TansParams = (params) => {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName]
		var part = encodeURIComponent(propName) + "="
		if (value !== null && value !== "" && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']'
						var subPart = encodeURIComponent(params) + "="
						result += subPart + encodeURIComponent(value[key]) + "&"
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&"
			}
		}
	}
	return result
}

// 重复点击提示
export const repeatClick = (txt = '请勿重复点击') => {
	Toast.alert(txt);
	return;
}
// 获取缓存的登录信息
export const getStortLogin = async () => {
	// console.log('getStortLogin')
	let data = await new Promise((r,p) =>{
		uni.getStorage({
			key: 'userInfo',
			success: (res) => {
				// console.log(res, '------res')
				let userInfo = res.data || {}
				store.commit('SET_TOKEN', userInfo.token)
				store.commit('SET_USERINFO', userInfo)
				r(userInfo)
			},
			fail: (error) => {
				console.log(error)
				r({})
			}
		})
	})
	return data;
}

// 退出登录
export const unLoginUser = async () => {
	Request({
		url: '/api/user/detail',
		method: 'POST', 
	}).then(res => {
		uni.setStorage({
			key: 'userInfo',
				data: {},
				success: () => {
				  console.log('数据存储成功');
				  getStortLogin()
				  uni.switchTab({
				  	url: '/pages/index/index'
				  })
				},
				fail: (err) => {
				  console.error('存储失败:', err);
				}
		})
	})
}
// 获取用户信息
export const getUserInfo = (token) => {
	Request({
		url: '/api/user/detail',
		method: 'POST', 
	}).then(res => {
		res.data.token = token || store.state.user.token
		uni.setStorage({
			key: 'userInfo',
			data: res.data,
			success: () => {
			  console.log('数据存储成功');
			},
			fail: (err) => {
			  console.error('存储失败:', err);
			}
		})
		store.commit('SET_USERINFO', res.data);	
	})
	
}
// 支付逻辑
export const payFun = (payType, data) => {
	Request({
		url: '/api/pay/pay',
		method: 'POST',
		data
	}).then(res => {
		// 支付宝微信付款
		if (payType == 0 || payType == 1) {
			let payT = ['wxpay','alipay']
			uni.requestPayment({
				provider: payT[payType], // 支付
				orderInfo: res.data.order_info, // 支付宝交易号
				...res.data,
				success(res) {	
					console.log('支付成功:', res);
					uni.redirectTo({
						url: `/pages/pay/pay?order_showid=${data.order_id}&order_id=${data.ordersn}&type=zfcg`,
						success: res => {},
						fail: () => {},
						complete: () => {}
					})
				},
				fail(err) {
					console.error('支付失败:', err);
					data.payType = payType
					uni.setStorage({
						key: 'payData', // 存储键名
						data: data,
						success: () => {
							uni.redirectTo({
								url: `/pages/pay/pay?order_showid=${data.order_id}&order_id=${data.ordersn}&type=zfsb`,
								success: res => {},
								fail: () => {},
								complete: () => {}
							})
						},
						fail: (err) => {
							console.error('存储失败:', err);
						}
					});
				}
			});
		}
		// 余额付款
		if (payType == 2) {
			let url = `/pages/pay/pay?order_showid=${data.order_id}&order_id=${data.ordersn}&type=${res.code == 0 ? 'zfcg' : 'zfsb'}`
			uni.redirectTo({
				url,
				success: res => {},
				fail: () => {},
				complete: () => {}
			})
		}
	}).catch(res => {
		console.log(payType)
		if (payType == 2) {
			let url = `/pages/pay/pay?order_showid=${data.order_id}&order_id=${data.ordersn}&type=${res.code == 0 ? 'zfcg' : 'zfsb'}`
			uni.setStorage({
				key: 'payData', // 存储键名
				data: data,
				success: () => {
					uni.redirectTo({
						url,
						success: res => {},
						fail: () => {},
						complete: () => {}
					})
				},
				})
		}
	})
	return;
}

// 订单功能
export const orderFun = async (type, data={}) => {
	let urlObj = {
		'confirmOrder': '/api/order/confirmOrder',
		'cancelOrder': '/api/order/cancelOrder',
		'urgeOrder': '/api/order/urgeOrder'
	}
	if (!urlObj[type]) return false
	let res = await Request({
		url: urlObj[type],
		method: 'POST',
		data
	})
	Toast.alert(res.msg);
	return res
}

// 判断用户是否存在支付密码
export const isPayPassword = (type, data={}) => {
	console.log(store.state.user)
	if (!store.state.user.userInfo.detail.pay_password) {
		uni.showModal({
			title: '设置支付密码',
			content: `是否前往设置支付密码`,
			showCancel: true,
			cancelText: '取消',
			confirmText: '确认',
			success: function(e) {
				if (e.confirm) {
					uni.navigateTo({
						url: '/pages/sePaytPassword/sePaytPassword'
					})
				}
			}
		});
		return false
	}
	// Toast.alert(res.msg);
	return true
}